<?php

namespace App\Kuafu\Base\Model\Traits;

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

trait KfSplitRelation
{
    public function hasOneWithTable($related, $foreignKey, $localKey, $table, string $connect = ''): HasOne
    {
        $instance = (new $related)->setTable($table);
        if (!empty($connect)) {
            $instance = $instance->setConnection($connect);
        }
        $foreignKey = $foreignKey ?: $this->getForeignKey();
        $localKey   = $localKey ?: $this->getKeyName();
        return new HasOne($instance->newQuery(), $this, $instance->getTable() . '.' . $foreignKey, $localKey);
    }

    public function hasManyWithTable($related, $foreignKey, $localKey, $table, string $connect = ''): HasMany
    {
        $instance   = (new $related)->setTable($table)->setConnection($connect);
        $foreignKey = $foreignKey ?: $this->getForeignKey();
        $localKey   = $localKey ?: $this->getKeyName();
        return new HasMany($instance->newQuery(), $this, $instance->getTable() . '.' . $foreignKey, $localKey);
    }
}
